"use client"

import { ArrowLeft, User } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useRouter } from "next/navigation"
import { useState, useRef, useEffect } from "react"
import { useToast } from "@/components/ui/use-toast"
import ReactMarkdown from 'react-markdown'
import { useAuth } from "@/lib/auth/auth-context"

interface SimpleIngredient {
  name: string;
  amount: string;
  color: string;
}

interface SimpleRecipe {
  category: string;
  nameEn: string;
  nameZh: string;
  ingredients: SimpleIngredient[];
  method: string[];
}

interface Ingredient {
  name: string;
  nameEn: string;
  amount: string;
  unit: string;
  color: string | null;
  note: string;
}

interface Recipe {
  category: string;
  nameEn: string;
  nameZh: string;
  difficulty: number;
  ingredients: Ingredient[];
  method: string[];
  glass: string;
  garnish: string;
  tips: string[];
}

interface RecipeCard {
  explanation: string;
  recipe: Recipe;
}

export default function ChatPage() {
  const router = useRouter()
  const bottomRef = useRef<HTMLDivElement>(null)
  const { toast } = useToast()
  const { user, isAuthenticated } = useAuth()
  
  const [messages, setMessages] = useState<Array<{role: string, content: string}>>([])
  const [input, setInput] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [recipeCards, setRecipeCards] = useState<{[key: number]: any}>({})
  const [loadingRecipes, setLoadingRecipes] = useState<{[key: number]: boolean}>({})
  const [displayedContent, setDisplayedContent] = useState<string>("")
  const [savingRecipe, setSavingRecipe] = useState<{[key: number]: boolean}>({})

  // 自动滚动到底部
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages, recipeCards])

  // 处理待处理的问题
  useEffect(() => {
    const pendingQuestion = localStorage.getItem('pendingQuestion')
    const selectedCategory = localStorage.getItem('selectedCategory')
    
    if (pendingQuestion && selectedCategory) {
      const formattedQuestion = `关于${selectedCategory}：${pendingQuestion}`
      localStorage.removeItem('pendingQuestion')
      localStorage.removeItem('selectedCategory')
      
      handleSubmit(formattedQuestion)
    }
  }, [])

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement> | string) => {
    if (e instanceof Event) {
      e.preventDefault()
    }
    
    const message = typeof e === 'string' ? e : input
    if (!message.trim()) return

    try {
      setIsLoading(true)
      
      // 创建新的消息数组
      const newMessages = [...messages, { role: 'user', content: message }]
      // 更新消息状态
      setMessages(newMessages)
      setInput("")

      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: newMessages  // 使用新创建的消息数组
        }),
      })

      if (!response.ok) {
        throw new Error('发送消息失败')
      }

      const data = await response.json()
      
      // 添加助手消息
      const fullContent = data.content
      setDisplayedContent("")

      // 逐字显示内容
      function updateDisplayContent(prev: string, content: string) {
        return prev + content;
      }
      
      for (let i = 0; i < fullContent.length; i++) {
        setTimeout(() => {
          setDisplayedContent((prev) => updateDisplayContent(prev, fullContent[i]))
        }, 40 * i)
      }

      setMessages(prev => [...prev, { role: 'assistant', content: fullContent }])
      
    } catch (error) {
      console.error('Chat error:', error)
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "发送消息失败，请重试",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 处理生成配方卡片
  const handleGenerateRecipe = async (content: string, index: number) => {
    try {
      setLoadingRecipes(prev => ({ ...prev, [index]: true }))
      const response = await fetch("/api/recipe", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      if (data.error) {
        throw new Error(data.error)
      }

      setRecipeCards(prev => ({ ...prev, [index]: data }))
    } catch (error) {
      console.error("Recipe generation error:", error)
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "生成配方失败，请重试",
        variant: "destructive",
      })
    } finally {
      setLoadingRecipes(prev => ({ ...prev, [index]: false }))
    }
  }

  // 保存配方到个人酒柜
  const handleSaveRecipe = async (index: number) => {
    if (!isAuthenticated) {
      toast({
        title: "请先登录",
        description: "保存配方需要先登录账号",
        variant: "destructive",
      })
      return
    }
    
    setSavingRecipe(prev => ({ ...prev, [index]: true }))
    
    try {
      const response = await fetch('/api/cabinet/save', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${user.token}`
        },
        body: JSON.stringify({ 
          recipe: recipeCards[index]
        }),
      })
      
      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || '保存失败')
      }
      
      const data = await response.json()
      
      if (!data.success) {
        throw new Error(data.error || '保存失败')
      }
      
      toast({
        title: "保存成功",
        description: "配方已保存到您的酒柜",
      })
      
      // 标记为已保存
      setRecipeCards(prev => ({
        ...prev,
        [index]: {
          ...prev[index],
          saved: true,
          recipeId: data.recipeId
        }
      }))
    } catch (error) {
      toast({
        title: "保存失败",
        description: error instanceof Error ? error.message : "保存配方时出现问题，请重试",
        variant: "destructive",
      })
    } finally {
      setSavingRecipe(prev => ({ ...prev, [index]: false }))
    }
  }

  // 渲染消息内容
  const renderMessage = (content: string, index: number) => {
    // 改进配方检测逻辑
    const hasRecipeKeywords = (
      (content.includes("配料") || content.includes("材料") || content.includes("成分")) &&
      (content.includes("步骤") || content.includes("制作") || content.includes("调制")) &&
      (content.includes("毫升") || content.includes("ml") || content.includes("克") || content.includes("g"))
    );

    return (
      <div className="space-y-4">
        {/* 显示助手消息内容 */}
        <div className="text-gray-700 text-base leading-relaxed prose">
          <ReactMarkdown>{index === messages.length - 1 ? displayedContent : content}</ReactMarkdown>
        </div>
        
        {/* 如果内容包含配方相关关键词，显示生成配方卡片按钮 */}
        {hasRecipeKeywords && !recipeCards[index] && (
          <div>
            <Button 
              variant="outline" 
              size="sm" 
              className="text-emerald-600 border-emerald-600"
              onClick={() => handleGenerateRecipe(content, index)}
              disabled={loadingRecipes[index]}
            >
              {loadingRecipes[index] ? "生成中..." : "生成配方卡片"}
            </Button>
          </div>
        )}

        {/* 显示配方卡片 */}
        {recipeCards[index] && (
          <div className="mt-4 bg-white rounded-lg shadow p-6">
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <div>
                  <h2 className="text-2xl font-serif">{recipeCards[index].nameEn}</h2>
                  <h3 className="text-xl font-serif">{recipeCards[index].nameZh}</h3>
                </div>
                
                {!recipeCards[index].saved && (
                  <Button 
                    variant="outline" 
                    size="sm"
                    className="text-emerald-600 border-emerald-600"
                    onClick={() => handleSaveRecipe(index)}
                    disabled={savingRecipe[index]}
                  >
                    {savingRecipe[index] ? "保存中..." : "保存到酒柜"}
                  </Button>
                )}
                
                {recipeCards[index].saved && (
                  <div className="text-sm text-emerald-600">已保存</div>
                )}
              </div>
              <div className="w-full h-0.5 bg-black"></div>
            </div>

            <div className="mt-8 space-y-4">
              <h4 className="text-lg">Ingredients 成分</h4>
              <div className="flex flex-col gap-4">
                <div className="flex items-center gap-4">
                  {recipeCards[index].ingredients.map((ing: SimpleIngredient, i: number) => (
                    <div 
                      key={i} 
                      className="flex flex-col items-center gap-2" 
                      style={{ flex: '1' }}
                    >
                      <div 
                        className="h-8 w-full rounded-sm" 
                        style={{ backgroundColor: ing.color }}
                      ></div>
                      <span className="text-sm text-gray-600 whitespace-nowrap">{ing.name}</span>
                    </div>
                  ))}
                </div>
                {recipeCards[index].ingredients.map((ing: SimpleIngredient, i: number) => (
                  <div key={i} className="flex items-center justify-between">
                    <span>{ing.name}</span>
                    <span>{ing.amount}</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="mt-8 space-y-4">
              <h4 className="text-lg">Method</h4>
              <ol className="list-decimal list-inside space-y-2">
                {recipeCards[index].method.map((step: string, i: number) => (
                  <li key={i} className="text-gray-700">{step}</li>
                ))}
              </ol>
            </div>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-[#f9f8f6]">
      {/* Header */}
      <div className="fixed top-0 left-0 right-0 bg-white border-b z-10">
        <div className="max-w-3xl mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center">
            <Button variant="ghost" size="icon" onClick={() => router.push("/")} className="mr-2">
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <h1 className="text-lg font-medium">ByteSlinger 调酒师</h1>
          </div>
          
          {isAuthenticated && (
            <Button 
              variant="ghost" 
              className="flex items-center gap-2"
              onClick={() => router.push("/profile")}
            >
              <User className="h-4 w-4" />
              <span>{user?.name}</span>
            </Button>
          )}
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-3xl mx-auto px-4 pt-16 pb-24">
        <div className="space-y-6">
          {messages.map((message, index) => (
            <div
              key={index}
              className={`flex ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`p-4 rounded-2xl inline-block max-w-[85%] ${
                  message.role === "user"
                    ? "bg-emerald-500 text-white"
                    : "bg-white text-gray-800"
                }`}
              >
                {message.role === "user" ? (
                  <p className="whitespace-pre-wrap">{message.content}</p>
                ) : (
                  renderMessage(message.content, index)
                )}
              </div>
            </div>
          ))}

          {/* Loading indicator */}
          {isLoading && (
            <div className="flex justify-start">
              <div className="bg-white p-4 rounded-2xl inline-block max-w-[80%]">
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-emerald-400 rounded-full animate-bounce [animation-delay:-0.3s]"></div>
                  <div className="w-2 h-2 bg-emerald-400 rounded-full animate-bounce [animation-delay:-0.15s]"></div>
                  <div className="w-2 h-2 bg-emerald-400 rounded-full animate-bounce"></div>
                </div>
              </div>
            </div>
          )}

          {/* 用于滚动的参考点 */}
          <div ref={bottomRef} />
        </div>
      </div>

      {/* Input Area */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t">
        <div className="max-w-3xl mx-auto">
          <form onSubmit={handleSubmit} className="flex gap-2 p-4">
            <Input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault()
                  handleSubmit(input)
                }
              }}
              placeholder="继续询问或寻求推荐..."
              className="flex-1"
              disabled={isLoading}
            />
            <Button type="submit" disabled={isLoading}>
              {isLoading ? "发送中..." : "发送"}
            </Button>
          </form>
        </div>
      </div>
    </div>
  )
}

